<?php

namespace app\api\controller\admin;

use app\admin\model\Admin;
use app\common\controller\TApi;
use Exception;
use think\Db;
use think\Collection;
use think\Log;

/**
 * 行政接口
 */
class Approve extends TApi
{
    protected $noNeedLogin = ['statusList'];
    protected $noNeedRight = ['*'];
    protected $status_0 = 0; //待审核
    protected $status_1 = 1;
    protected $status_2 = 2;
    protected $status_3 = 3;
    protected $status_300 = 300;
    protected $status_301 = 301;
    protected $status_302 = 302;
    protected $status_303 = 303;
    protected $status_4 = 4;
    protected $status_5 = 5;
    protected $status_6 = 6;
    protected $status_600 = 600;
    protected $status_601 = 601;
    protected $status_602 = 602;
    protected $status_603 = 603;
    protected $status_604 = 604;
    protected $status_7 = 7;
    protected $status_8 = 8;
    protected $status_9 = 9;
    protected $categoryArr = ['contract', 'seal', 'askfor', 'usecar', 'refuel', 'carep', 'functional', 'patrol', 'issues', 'travel', 'official', 'daily', 'expen', 'food', 'classify', 'procure'];
    protected $materialArr = ['daily', 'expen', 'food'];
    protected $letArr = ['classify'];
    
    protected $returnArr = ['daily', 'seal'];
    protected $enterArr = ['usecar', 'refuel'];

    //行政列表
    public function approveList()
    {                
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $type = $this->request->get('type');
        $category = $this->request->get('category');
        if (!$category) {
            $this->error('行政类型未传');
        }
        if (!in_array($category, $this->categoryArr)) {
            $this->error('行政类型错误');
        }
        $search = $this->request->get('search');

        $url = 'api/admin/approve/'.$category;
        $authority = new \app\api\controller\admin\Authority;
        $falg = $authority->isAuth($url);
        if(!$falg) {
            $this->error('无权限，请联系管理员');
        }

        $admin = $this->auth->getAdmininfo();

        $fieldStr = 'are.*,FROM_UNIXTIME(are.createtime,"%Y-%m-%d %H:%i:%s") as createtime,dti.status as istodo,admin.nickname as adminfame';
        $joinArr = [
            ['dts_todo_items dti', 'dti.id = are.todo_id and dti.admin_id = '.$admin['id'], 'left'],
            ['admin admin', 'admin.id = are.admin_id', 'left'],
        ];
        $query = []; $query1 = [];
        $queryRaw = '';
        $queryOrRaw = '';
        $group = '';

        switch ($category) {
            case 'contract':
                $fieldStr = $fieldStr . ',are.name,are.filingsno';
                if ($type) {
                    $queryRaw = '(are.status != 7 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status not in (0,600,7) and are.examine_leader_id = ' . $admin['id'] . ') or (are.status not in (0,1,600,601,7) and are.examine_finance_id = ' . $admin['id'] . ') or (are.status in (3,4,5,603,604) and are.examine_advisor_id = ' . $admin['id'] . ') or (are.status in (4,5,604) and are.examine_legal_id = ' . $admin['id'] . ')';
                    $queryOrRaw = 'are.status = ' . $this->status_5 . ' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'seal':
                $fieldStr = $fieldStr . ',config.name as configname,are.fortime';
                $joinArr[] = ['dts_config_seal config', 'config.id = are.config_seal_id', 'left'];
                if ($type) {
                    $queryRaw = 'are.status != ' . $this->status_1 . '  and are.examine_dept_id = ' . $admin['id'];
                    $queryOrRaw = 'are.status in ('.$this->status_2.','.$this->status_5.') and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'askfor':
                $fieldStr = $fieldStr . ',config.name as configname,are.fortime,are.fordate,are.duration';
                $joinArr[] = ['dts_config_askfor config', 'config.id = are.config_askfor_id', 'left'];
                if ($type) {
                    $queryRaw = 'are.status != ' . $this->status_3 . '  and are.examine_dept_id = ' . $admin['id'];
                    $queryOrRaw = 'are.status = '. $this->status_1 .' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'usecar':
                $fieldStr = $fieldStr . ',config.name as configname,are.fortime,are.fordate';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                if ($type == 1) {
                    $queryRaw = 'are.status != 1 and are.examine_vehicle_id = ' . $admin['id'];
                }elseif($type == 2){
                    $queryRaw = 'are.status in(4,5) and are.enter_driver_id = ' . $admin['id'];
                }else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'refuel':
                $fieldStr = $fieldStr . ',config.name as configname,are.fortime';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                if ($type == 1) {
                    $queryRaw = 'are.status != 3 and are.examine_dept_id = ' . $admin['id'];
                }elseif($type == 2){
                    $queryRaw = 'are.status in(1,4) and are.enter_driver_id = ' . $admin['id'];
                }else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'carep':
                $fieldStr = $fieldStr . ',config.name as configname';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                if ($type) {
                    $queryRaw = '(are.status != 4 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status in (1,2,301) and are.examine_leader_id = ' . $admin['id'] . ')';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'functional':
                $fieldStr = $fieldStr . ',config.name as configname,are.fortime,are.fordate';
                $joinArr[] = ['dts_config_functional config', 'config.id = are.config_functional_id', 'left'];
                if ($type) {
                    $queryRaw = 'are.status != 3 and are.examine_dept_id = ' . $admin['id'];
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'patrol':
                $fieldStr = $fieldStr . ',are.severity,are.location,examinedept.nickname as examinedeptfame';
                if ($type) {
                    $queryRaw = 'are.status != 3 and are.examine_dept_id = ' . $admin['id'];
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.location|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                break;
            case 'issues':
                $fieldStr = $fieldStr . ',are.fortime,are.forcause';
                if ($type) {
                    $queryRaw = '(are.status != 4 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status in (1,2,301) and are.examine_leader_id = ' . $admin['id'] . ')';
                    $queryOrRaw = 'are.status = ' . $this->status_2 . ' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.forcause|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'travel':
                $fieldStr = $fieldStr . ',are.forcause,are.travel_mode,are.board_lodging';
                if ($type) {
                    $queryRaw = '(are.status != 7 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status not in (0,600,7) and are.examine_leader_id = ' . $admin['id'] . ') or (are.status not in (0,1,600,601,7) and are.examine_finance_id = ' . $admin['id'] . ') or (are.status in (3,4,5,603,604) and are.examine_advisor_id = ' . $admin['id'] . ') or (are.status in (4,5,604) and are.examine_legal_id = ' . $admin['id'] . ')';
                    $queryOrRaw = 'are.status = ' . $this->status_5 . ' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.forcause|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'official':
                $fieldStr = $fieldStr . ',are.title,are.textno,are.fortime,are.severity';
                if ($type) {
                    $queryRaw = '(are.status != 4 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status not in (0,300,4) and are.examine_leader_id = ' . $admin['id'] . ')';
                    $queryOrRaw = 'are.status = ' . $this->status_5 . ' and FIND_IN_SET(' . $admin['id'] . ',are.dishout_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.title|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'daily':    
                $fieldStr = $fieldStr . ',are.letname,are.fortime,are.forcause';
                if ($type) {
                    $queryRaw = 'are.status != 1 and are.examine_dept_id = ' . $admin['id'];
                    $queryOrRaw = 'are.status in ('.$this->status_3.','.$this->status_4.','.$this->status_5.','.$this->status_6.','.$this->status_7.') and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                }else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $status = $this->request->get('status');
                if($status) {
                    $joinArr = [
                        ['dts_todo_items dti', 'dti.approve_id = are.id and dti.admin_id = '.$admin['id'], 'left'],
                        ['admin admin', 'admin.id = are.admin_id', 'left'],
                    ];
                    $query = ['are.status' => ['in', explode(',', $status)], 'are.giveout_id' => $admin['id']];
                    $queryRaw = '';
                    $queryOrRaw = '';
                }
                $query1 = $search ? ['are.letname|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                $group = 'are.id';
                break;
            case 'expen':
            case 'food':
                $fieldStr = $fieldStr . ',are.letname,are.forcause';
                if ($type) {
                    $queryRaw = 'are.status != 1 and are.examine_dept_id = ' . $admin['id'];
                    $queryOrRaw = 'are.status in ('.$this->status_3.','.$this->status_4.','.$this->status_5.') and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                }else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $status = $this->request->get('status');
                if($status) {
                    $joinArr = [
                        ['dts_todo_items dti', 'dti.approve_id = are.id and dti.admin_id = '.$admin['id'], 'left'],
                        ['admin admin', 'admin.id = are.admin_id', 'left'],
                    ];
                    $query = ['are.status' => ['in', explode(',', $status)], 'are.giveout_id' => $admin['id']];
                    $queryRaw = '';
                    $queryOrRaw = '';
                }
                $query1 = $search ? ['are.letname|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                $group = 'are.id';
                break;
            case 'classify':
                $fieldStr = $fieldStr . ',config.name as configname,are.location,examinedept.nickname as examinedeptfame';
                $joinArr[] = ['dts_config_files config', 'config.id = are.config_files_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                if ($type) {
                    $queryRaw = 'are.status != 3 and are.examine_dept_id = ' . $admin['id'];
                    $queryOrRaw = 'are.status = '. $this->status_1 .' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.location|config.name|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
            case 'procure':
                $fieldStr = $fieldStr . ',are.fortime,are.forcause,are.budget_amount_float,are.budget_amount_string,dept.name as dept_name,class.name as class_name';
                $joinArr[] = ['dts_dept dept', 'dept.id = are.dept_id', 'left'];
                $joinArr[] = ['dts_classes class', 'class.id = are.classes_id', 'left'];
                if ($type) {
                    $queryRaw = '(are.status != 4 and are.examine_dept_id = ' . $admin['id'] . ') or (are.status not in (0,300,4) and are.examine_leader_id = ' . $admin['id'] . ')';
                    $queryRaw .= ' or (are.status not in (0,1,300,301,4) and are.examine_fenguan_id = ' . $admin['id'] . ') or (are.status not in (0,1,2,300,301,302,4) and are.examine_yuanchang_id = ' . $admin['id'] . ')';
                    $queryOrRaw = 'are.status = ' . $this->status_5 . ' and FIND_IN_SET(' . $admin['id'] . ',are.copy_ids) > 0';
                } else {
                    $query = ['are.admin_id' => $admin['id']];
                }
                $query1 = $search ? ['are.forcause|admin.nickname' => ['LIKE', '%'.$search.'%']] : [];
                break;
        }

        $dbname = 'dts_approve_' . $category;
        if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
            $dbname = 'dts_approve_' . $category . '_let';
        }

        $dbmodel = Db::name($dbname)->alias('are')->field($fieldStr)->join($joinArr);
        if ($query) {
            $dbmodel = $dbmodel->where($query);
        }
        if($query1) {
            $dbmodel = $dbmodel->where($query1);
        }
        if ($queryRaw) {
            $dbmodel = $dbmodel->whereRaw($queryRaw);
        }
        if ($queryOrRaw) {
            $dbmodel = $dbmodel->whereOrRaw($queryOrRaw);
        }

        if ($group) {
            $list = $dbmodel->group($group)->order('are.createtime', 'desc')->paginate($pagesize, false, ['page' => $page]);
        } else {
            $list = $dbmodel->order('are.createtime', 'desc')->paginate($pagesize, false, ['page' => $page]);
        }

        $this->success('success', $list);
    }

    //行政详情
    public function approveInfo()
    {

        $approveId = $this->request->get('approveId');
        $category = $this->request->get('category');
        if (!$approveId || !$category) {
            $this->error('未提交查询参数');
        }
        if (!in_array($category, $this->categoryArr)) {
            $this->error('行政类型错误');
        }

        $query = ['are.id' => $approveId];
        $fieldStr = 'are.*,FROM_UNIXTIME(are.createtime,"%Y-%m-%d %H:%i:%s") as createtime,FROM_UNIXTIME(are.updatetime,"%Y-%m-%d %H:%i:%s") as updatetime,admin.avatar as adminavatar,admin.nickname as adminfame';
        $joinArr = [
            ['admin admin', 'admin.id = are.admin_id', 'left']
        ];

        switch ($category) {
            case 'contract':
                $fieldStr = $fieldStr . ',undertakedept.name as undertakedeptname,
                undertakeadmin.avatar as undertakeadminavatar,undertakeadmin.nickname as undertakeadminfame,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                examinefinance.avatar as examinefinanceavatar,examinefinance.nickname as examinefinancefame,
                examineadvisor.avatar as examineadvisoravatar,examineadvisor.nickname as examineadvisorfame,
                examinelegal.avatar as examinelegalavatar,examinelegal.nickname as examinelegalfame,
                GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['dts_dept undertakedept', 'undertakedept.id = are.undertake_dept_id', 'left'];
                $joinArr[] = ['admin undertakeadmin', 'undertakeadmin.id = are.undertake_admin_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['admin examinefinance', 'examinefinance.id = are.examine_finance_id', 'left'];
                $joinArr[] = ['admin examineadvisor', 'examineadvisor.id = are.examine_advisor_id', 'left'];
                $joinArr[] = ['admin examinelegal', 'examinelegal.id = are.examine_legal_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'seal':
                $fieldStr = $fieldStr . ',config.name as configname,examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['dts_config_seal config', 'config.id = are.config_seal_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'askfor':
                $fieldStr = $fieldStr . ',config.name as configname,examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['dts_config_askfor config', 'config.id = are.config_askfor_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'usecar':
                $fieldStr = $fieldStr . ',config.name as configname,enroll.avatar as enrollavatar,enroll.nickname as enrollname,
                GROUP_CONCAT(DISTINCT passenger.avatar) as passengeravatars,GROUP_CONCAT(DISTINCT passenger.nickname) as passengerfames,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                driver.avatar as driveravatar,driver.nickname as driverfame';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                $joinArr[] = ['admin enroll', 'enroll.id = config.admin_id', 'left'];
                $joinArr[] = ['admin passenger', 'FIND_IN_SET(passenger.id,are.passenger_ids)', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_vehicle_id', 'left'];
                $joinArr[] = ['admin driver', 'driver.id = are.enter_driver_id', 'left'];
                break;
            case 'refuel':
                $fieldStr = $fieldStr . ',config.name as configname,
                enroll.avatar as enrollavatar,enroll.nickname as enrollname,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                driver.avatar as driveravatar,driver.nickname as driverfame';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                $joinArr[] = ['admin enroll', 'enroll.id = config.admin_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin driver', 'driver.id = are.enter_driver_id', 'left'];
                break;
            case 'carep':
                $fieldStr = $fieldStr . ',config.name as configname,
                enroll.avatar as enrollavatar,enroll.nickname as enrollname,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                far.avatar as repairavatar,far.nickname as repairfame,dfr.status as repairstatus,dfr.repair_msg,dfr.repair_files';
                $joinArr[] = ['dts_config_bus config', 'config.id = are.config_bus_id', 'left'];
                $joinArr[] = ['admin enroll', 'enroll.id = config.admin_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['dts_fault_repair dfr', 'dfr.related_id = are.id and category = "bus"', 'left'];
                $joinArr[] = ['admin far', 'far.id = dfr.repair_id', 'left'];
                break;
            case 'functional':
                $fieldStr = $fieldStr . ',config.name as configname,examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame';
                $joinArr[] = ['dts_config_functional config', 'config.id = are.config_functional_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                break;
            case 'patrol':
                $fieldStr = $fieldStr . ',examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame';
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                break;
            case 'issues':
                $fieldStr = $fieldStr . ',
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'travel':
                $fieldStr = $fieldStr . ',GROUP_CONCAT(DISTINCT travel.nickname) as travelname,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                examinefinance.avatar as examinefinanceavatar,examinefinance.nickname as examinefinancefame,
                examineadvisor.avatar as examineadvisoravatar,examineadvisor.nickname as examineadvisorfame,
                examinelegal.avatar as examinelegalavatar,examinelegal.nickname as examinelegalfame,
                GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['admin travel', 'FIND_IN_SET(travel.id,are.travel_ids)', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['admin examinefinance', 'examinefinance.id = are.examine_finance_id', 'left'];
                $joinArr[] = ['admin examineadvisor', 'examineadvisor.id = are.examine_advisor_id', 'left'];
                $joinArr[] = ['admin examinelegal', 'examinelegal.id = are.examine_legal_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'official':
                $fieldStr = $fieldStr . ',config.name as configname,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                GROUP_CONCAT(DISTINCT dishout.nickname) as dishoutname';
                $joinArr[] = ['dts_config_files config', 'config.id = are.config_files_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['admin dishout', 'FIND_IN_SET(dishout.id,are.dishout_ids)', 'left'];
                break;
            case 'daily':    
            case 'expen':
            case 'food':
                $fieldStr = $fieldStr . ',
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                giveout.avatar as giveoutavatar,giveout.nickname as giveoutfame,
                GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin giveout', 'giveout.id = are.giveout_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'classify':
                $fieldStr = $fieldStr . ',config.name configname,type.name as typename,label.name as labelname,examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['dts_config_files config', 'config.id = are.config_files_id', 'left'];
                $joinArr[] = ['dts_config_classify_type type', 'type.id = are.config_classify_type_id', 'left'];
                $joinArr[] = ['dts_config_classify_label label', 'label.id = are.config_classify_label_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;
            case 'procure':
                $fieldStr = $fieldStr . ',dept.name deptname,classes.name as classesname,capital.name as capitalname,
                examinedept.avatar as examinedeptavatar,examinedept.nickname as examinedeptfame,
                examineleader.avatar as examineleaderavatar,examineleader.nickname as examineleaderfame,
                fenguan.avatar as fenguanavatar,fenguan.nickname as fenguanfame,
                yuanchang.avatar as yuanchangavatar,yuanchang.nickname as yuanchangfame,
                GROUP_CONCAT(DISTINCT copy.nickname) as copyname';
                $joinArr[] = ['dts_dept dept', 'dept.id = are.dept_id', 'left'];
                $joinArr[] = ['dts_classes classes', 'classes.id = are.classes_id', 'left'];
                $joinArr[] = ['dts_config_capital capital', 'capital.id = are.config_capital_id', 'left'];
                $joinArr[] = ['admin examinedept', 'examinedept.id = are.examine_dept_id', 'left'];
                $joinArr[] = ['admin examineleader', 'examineleader.id = are.examine_leader_id', 'left'];
                $joinArr[] = ['admin fenguan', 'fenguan.id = are.examine_fenguan_id', 'left'];
                $joinArr[] = ['admin yuanchang', 'yuanchang.id = are.examine_yuanchang_id', 'left'];
                $joinArr[] = ['admin copy', 'FIND_IN_SET(copy.id,are.copy_ids)', 'left'];
                break;    
        }

        $dbname = 'dts_approve_' . $category;
        if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
            $dbname = 'dts_approve_' . $category . '_let';
        }
        $info = Db::name($dbname)->alias('are')->field($fieldStr)->join($joinArr)->where($query)->find();
    
        if(in_array($category, $this->materialArr)) {
            $info['log'] = Db::name('dts_approve_' . $category . '_log')->alias('log')
            ->field('log.*,material.name as materialname')
            ->join('dts_material_'.$category.' material', 'material.id = log.material_'.$category.'_id', 'left')
            ->where('log.'.$category.'_let_id', $info['id'])
            ->select();
        }
        if(in_array($category, $this->letArr)) {
            $info['log'] = Db::name('dts_approve_' . $category . '_log')->where($category.'_let_id', $info['id'])->select();
        }

        $examineList = Db::name('dts_approve_examine_log')->where(['category' => $category, 'approve_id' => $info['id']])->order('id', 'asc')->select();
        if($examineList) {
            foreach($examineList as $key => $item) {
                $temp = Db::name('admin')->field('avatar,nickname')->where('id', $item['examine_id'])->find();
                $examineList[$key]['examine_avatar'] = $temp['avatar'];
                $examineList[$key]['examine_name'] = $temp['nickname'];
            }
        }
        $info['examineList'] = $examineList;

        $apiService = new \app\api\controller\Service;
        $admin = $this->auth->getAdmininfo();
        $apiService->handletodoitem([$info['todo_id']], $admin['id']);
        $apiService->handletodoitembyapprove($info['id'], $admin['id']);

        $this->success('success', $info);
    }

    //行政申请
    public function approveApply()
    {

        $category = $this->request->post('category');
        if (!$category) {
            $this->error('行政类型未传');
        }
        if (!in_array($category, $this->categoryArr)) {
            $this->error('行政类型错误');
        }

        $data = [];
        $admin = $this->auth->getAdmininfo();
        $dept = $this->auth->getDeptInfo();
        if(!$dept) {
            $this->error('未绑定部门信息');
        }

        switch ($category) {
            case 'contract':
                $name = $this->request->post('name');
                $isprice = $this->request->post('isprice', 0);
                $enquirymsg = $this->request->post('enquirymsg');
                $filingsno = $this->request->post('filingsno');
                $undertake_dept_id = $this->request->post('undertake_dept_id');
                $undertake_admin_id = $this->request->post('undertake_admin_id');
                $undertake_time = $this->request->post('undertake_time');
                $performing_party = $this->request->post('performing_party');
                $content = $this->request->post('content');
                $pay_agree = $this->request->post('pay_agree');
                $pay_price = $this->request->post('pay_price');
                $pay_method = $this->request->post('pay_method');
                $copies_num = $this->request->post('copies_num');
                $deadline = $this->request->post('deadline');
                $remark = $this->request->post('remark');
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                $finance_id = $this->request->post('finance_id');
                $advisor_id = $this->request->post('advisor_id');
                $legal_id = $this->request->post('legal_id');
                if (
                    !$name || !$filingsno || !$undertake_dept_id || !$undertake_admin_id || !$undertake_time ||
                    !$performing_party || !$content || !$pay_agree || !$pay_price || !$pay_method || !$deadline || !$copies_num
                ) {
                    $this->error('请提交合同信息');
                }

                if (!$examine_id || !$leader_id || !$finance_id || !$advisor_id || !$legal_id) {
                    $this->error('未设置审批人');
                }

                $data = [
                    'name' => $name, 'isprice' => $isprice, 'enquirymsg' => $enquirymsg, 'filingsno' => $filingsno, 'undertake_dept_id' => $undertake_dept_id,
                    'undertake_admin_id' => $undertake_admin_id, 'undertake_time' => $undertake_time, 'performing_party' => $performing_party,
                    'content' => $content, 'pay_agree' => $pay_agree, 'pay_price' => $pay_price, 'pay_method' => $pay_method, 'copies_num' => $copies_num, 'deadline' => $deadline, 'remark' => $remark,
                    'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id, 'examine_finance_id' => $finance_id, 'examine_advisor_id' => $advisor_id, 'examine_legal_id' => $legal_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'seal':
                $config_seal_id = $this->request->post('config_seal_id');
                $fortime = $this->request->post('fortime');
                $forcause = $this->request->post('forcause');
                $isouter = $this->request->post('isouter');
                $returntime = $this->request->post('returntime');
                if (!$config_seal_id || !$fortime || !$forcause) {
                    $this->error('请提交用章信息'); 
                }
                $config = Db::name('dts_config_seal')->where('id', $config_seal_id)->find();
                if (!$config || !$config['examine_id']) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'config_seal_id' => $config_seal_id, 'fortime' => $fortime, 'forcause' => $forcause, 'isouter' => $isouter,
                    'examine_dept_id' => $config['examine_id'], 
                    'copy_ids' => $config['copy_ids']
                ];
                if($returntime) {
                    $data['returntime'] = $returntime;
                }
                break;
            case 'askfor':
                $config_askfor_id = $this->request->post('config_askfor_id');
                $fortime = $this->request->post('fortime');
                $fordate = $this->request->post('fordate');
                $duration = $this->request->post('duration');
                $forcause = $this->request->post('forcause');
                $files = $this->request->post('files');
                $examine_id = $this->request->post('examine_id');
                if (!$config_askfor_id || !$fortime || !$fordate || !$duration || !$forcause || !$examine_id) {
                    $this->error('请提交请假信息');
                }
                if (!$examine_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'config_askfor_id' => $config_askfor_id, 'fortime' => $fortime, 'fordate' => $fordate, 'duration' => $duration,
                    'forcause' => $forcause, 'files' => $files, 'examine_dept_id' => $examine_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'usecar':
                $fortime = $this->request->post('fortime');
                $fordate = $this->request->post('fordate');
                $beginplace = $this->request->post('beginplace');
                $endplace = $this->request->post('endplace');
                $forcause = $this->request->post('forcause');
                $examine_id = $this->request->post('examine_id');
                $passenger_ids = $this->request->post('passenger_ids');
                $passenger_json = $this->request->post('passenger_json');
                if (!$fortime || !$fordate || !$beginplace || !$endplace || !$forcause) {
                    $this->error('请提交用车信息');
                }
                if (!$examine_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'fortime' => $fortime, 'fordate' => $fordate, 'beginplace' => $beginplace, 'endplace' => $endplace, 'forcause' => $forcause, 
                    'examine_vehicle_id' => $examine_id
                ];
                if($passenger_ids) {
                    $data['passenger_ids'] = $passenger_ids;
                    $data['passenger_json'] = $passenger_json;
                }
                break;
            case 'refuel':
                $fortime = $this->request->post('fortime');
                $location = $this->request->post('location');
                $config_bus_id = $this->request->post('config_bus_id');
                $enter_driver_id = $this->request->post('enter_driver_id');
                $forcause = $this->request->post('forcause');
                if (!$fortime || !$location || !$config_bus_id || !$enter_driver_id || !$forcause) {
                    $this->error('请提交公车加油信息');
                }
                $config = Db::name('dts_config_bus')->where('id', $config_bus_id)->find();
                if (!$config || !$config['examine_id']) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'fortime' => $fortime, 'location' => $location, 'config_bus_id' => $config_bus_id, 'enter_driver_id' => $enter_driver_id,
                    'forcause' => $forcause, 'examine_dept_id' => $config['examine_id']
                ];
                break;
            case 'carep':
                $config_bus_id = $this->request->post('config_bus_id');
                $forcause = $this->request->post('forcause');
                $files = $this->request->post('files');
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                if (!$config_bus_id || !$forcause) {
                    $this->error('请提交公车维修信息');
                }
                if (!$examine_id || !$leader_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'config_bus_id' => $config_bus_id, 'forcause' => $forcause,  'files' => $files, 
                    'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id
                ];
                break;
            case 'functional':
                $fortime = $this->request->post('fortime');
                $fordate = $this->request->post('fordate');
                $config_functional_id = $this->request->post('config_functional_id');
                $forcause = $this->request->post('forcause');
                $isdevice = $this->request->post('isdevice', 0);
                $other_equipment = $this->request->post('other_equipment');
                if (!$fortime || !$fordate || !$config_functional_id || !$forcause) {
                    $this->error('请提交功能室信息');
                }
                $config = Db::name('dts_config_functional')->where('id', $config_functional_id)->find();
                if (!$config || !$config['examine_id']) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'fortime' => $fortime, 'fordate' => $fordate, 'config_functional_id' => $config_functional_id, 'forcause' => $forcause,
                    'isdevice' => $isdevice, 'other_equipment' => $other_equipment, 'examine_dept_id' => $config['examine_id'] 
                ];
                break;
            case 'patrol':
                $severity = $this->request->post('severity');
                $location = $this->request->post('location');
                $forcause = $this->request->post('forcause');
                $images = $this->request->post('images');
                $examine_id = $this->request->post('examine_id');
                if (!$severity || !$location || !$forcause || !$images || !$examine_id) {
                    $this->error('请提交巡查信息');
                }
                $num = Db::name('admin')->where('id', $examine_id)->count(1);
                if (!$num) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'severity' => $severity, 'location' => $location, 'forcause' => $forcause, 'images' => $images, 'examine_dept_id' => $examine_id
                ];
                break;
            case 'issues':
                $fortime = $this->request->post('fortime');
                $forcause = $this->request->post('forcause');
                $forcontent = $this->request->post('forcontent');
                $files = $this->request->post('files');
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                if (!$fortime || !$forcause || !$forcontent || !$files) {
                    $this->error('请提交事项信息');
                }
                if (!$examine_id || !$leader_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'fortime' => $fortime, 'forcause' => $forcause, 'forcontent' => $forcontent, 'files' => $files, 
                    'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'travel':
                $fillindate = $this->request->post('fillindate');
                $jobs = $this->request->post('jobs');
                $travel_ids = $this->request->post('travel_ids');
                $travel_ids_json = $this->request->post('travel_ids_json');
                $travel_num = $this->request->post('travel_num');
                $forcause = $this->request->post('forcause');
                $travel_mode = $this->request->post('travel_mode');
                $driver = $this->request->post('driver');
                $board_lodging = $this->request->post('board_lodging');
                $endplace = $this->request->post('endplace');
                $fortime = $this->request->post('fortime');
                $fordate = $this->request->post('fordate');
                $files = $this->request->post('files');
                $remark = $this->request->post('remark');
                if (!$fillindate || !$travel_ids || !$travel_num || !$forcause || !$travel_mode || !$board_lodging || !$endplace || !$fortime || !$fordate) {
                    $this->error('请提交差旅信息');
                }
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                $finance_id = $this->request->post('finance_id');
                $advisor_id = $this->request->post('advisor_id');
                $legal_id = $this->request->post('legal_id');
                if (!$examine_id || !$leader_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'fillindate' => $fillindate, 'jobs' => $jobs, 'travel_ids' => $travel_ids, 'travel_ids_json' => $travel_ids_json, 'travel_num' => $travel_num, 
                    'forcause' => $forcause, 'travel_mode' => $travel_mode, 'driver' => $driver, 'board_lodging' => $board_lodging, 'endplace' => $endplace,
                    'fortime' => $fortime, 'fordate' => $fordate, 'files' => $files, 'remark' => $remark, 
                    'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id, 'examine_finance_id' => $finance_id, 
                    'examine_advisor_id' => $advisor_id, 'examine_legal_id' => $legal_id, 'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'official':
                $config_files_id = $this->request->post('config_files_id');
                $title = $this->request->post('title');
                $textno = $this->request->post('textno');
                $fortime = $this->request->post('fortime');
                $files = $this->request->post('files');
                $division = $this->request->post('division');
                $severity = $this->request->post('severity');
                $remark = $this->request->post('remark');
                if (!$config_files_id || !$title || !$textno || !$fortime || !$files || !$division || !$severity) {
                    $this->error('请提交公文信息');
                }
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                if (!$examine_id || !$leader_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'config_files_id' => $config_files_id, 'title' => $title, 'textno' => $textno, 'fortime' => $fortime, 'files' => $files,
                    'division' => $division, 'severity' => $severity, 'remark' => $remark, 'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id
                ];
                break;
            case 'daily':
                $letname = $this->request->post('letname');
                $fortime = $this->request->post('fortime');
                $params = $this->request->post('params/a');//['materialId' => '物资Id', 'quantity' => '数量']
                $returntime = $this->request->post('returntime');
                $forcause = $this->request->post('forcause');
                $examine_id = $this->request->post('examine_id');
                $giveout_id = $this->request->post('giveout_id');
                if(!$letname || !$fortime || !$params || !$examine_id || !$giveout_id) {
                    $this->error('请提交需要的物资信息');
                }
                $data = [
                   'letname' => $letname, 'fortime' => $fortime, 'forcause' => $forcause, 'params' => $params, 'examine_dept_id' => $examine_id, 'giveout_id' => $giveout_id, 
                   'copy_ids' => $dept[$category.'_copy_ids']
                ];
                if($returntime) {
                    $data['returntime'] = $returntime;
                }
                break;
            case 'expen':
                $letname = $this->request->post('letname');
                $params = $this->request->post('params/a');//['materialId' => '物资Id', 'quantity' => '数量']
                $forcause = $this->request->post('forcause');
                $examine_id = $this->request->post('examine_id');
                $giveout_id = $this->request->post('giveout_id');
                if(!$letname || !$params || !$examine_id || !$giveout_id) {
                    $this->error('请提交需要的物资信息');
                }
                $data = [
                    'letname' => $letname, 'forcause' => $forcause, 'params' => $params, 'examine_dept_id' => $examine_id, 'giveout_id' => $giveout_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'food':   
                $letname = $this->request->post('letname');
                $params = $this->request->post('params/a');//['materialId' => '物资Id', 'quantity' => '数量']
                $forcause = $this->request->post('forcause');
                $examine_id = $this->request->post('examine_id');
                $giveout_id = $this->request->post('giveout_id');
                if(!$letname || !$params || !$examine_id || !$giveout_id) {
                    $this->error('请提交需要的物资信息');
                }
                $data = [
                    'letname' => $letname, 'forcause' => $forcause, 'params' => $params, 'examine_dept_id' => $examine_id, 'giveout_id' => $giveout_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'classify':
                $config_files_id = $this->request->post('config_files_id');
                $location = $this->request->post('location');
                $config_classify_type_id = $this->request->post('config_classify_type_id');
                $config_classify_label_id = $this->request->post('config_classify_label_id');
                $params = $this->request->post('params/a');//['name' => '文件', 'quantity' => '数量', 'filename' => '上次返回Id', 'fileurl' => '路径']
                if(!$config_files_id || !$location || !$params) {
                    $this->error('请提交归档信息');
                }
                $examine_id = $this->request->post('examine_id');
                if(!$examine_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'config_files_id' => $config_files_id, 'location' => $location, 'config_classify_type_id' => $config_classify_type_id, 
                    'config_classify_label_id' => $config_classify_label_id, 'params' => $params, 'examine_dept_id' => $examine_id, 
                    'copy_ids' => $dept[$category.'_copy_ids']
                ];
                break;
            case 'procure':
                $dept_id = $this->request->post('dept_id');
                $classes_id = $this->request->post('classes_id');
                $letname = $this->request->post('letname');
                $fortime = $this->request->post('fortime');
                $forcause = $this->request->post('forcause');
                $budget_amount_float = $this->request->post('budget_amount_float');
                $budget_amount_string = $this->request->post('budget_amount_string');
                $files = $this->request->post('files');
                $files_json = $this->request->post('files_json');
                $config_capital_id = $this->request->post('config_capital_id');
                $examine_id = $this->request->post('examine_id');
                $leader_id = $this->request->post('leader_id');
                $finance_id = $this->request->post('finance_id');
                $advisor_id = $this->request->post('advisor_id');
                $copy_ids = $this->request->post('copy_ids');
                if((!$dept_id && !$classes_id) || !$fortime || !$forcause || !$budget_amount_float || !$budget_amount_string || !$config_capital_id) {
                    $this->error('请提交事前信息');
                }
                if(!$examine_id || !$leader_id) {
                    $this->error('未设置审批人');
                }
                $data = [
                    'dept_id' => $dept_id, 'classes_id' => $classes_id, 'letname' => $letname, 'fortime' => $fortime, 
                    'forcause' => $forcause, 'budget_amount_float' => $budget_amount_float, 'budget_amount_string' => $budget_amount_string, 
                    'files' => $files,'config_capital_id' => $config_capital_id, 
                    'examine_dept_id' => $examine_id, 'examine_leader_id' => $leader_id,
                    'examine_fenguan_id' => $finance_id, 'examine_yuanchang_id' => $advisor_id,
                    'copy_ids' => $copy_ids
                ];
                if($files_json) {
                    $data['files_json'] = html_entity_decode($files_json);
                }
                break;   
        }

        //路径在app/common/model
        $row = __db(function () use ($category, $data, $admin, $dept) {
            //待办事项
            $title = __('Approve ' . $category) . '申请';
            $apiService = new \app\api\controller\Service;
            if($category == 'usecar') {
                $todoItems = $apiService->savetodoitem($title, $category, $data['examine_vehicle_id']);
            }else {
                $todoItems = $apiService->savetodoitem($title, $category, $data['examine_dept_id']);
            }
            
            //保存申请
            $data['todo_id'] = $todoItems['id'];
            $data['admin_id'] = $admin['id'];
            $data['deptId'] = $dept['id'];
            $data['deptname'] = $dept['name'];

            if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
                $params = $data['params'];
                unset($data['params']);
                $letModel = model('model/dts/approve/' . $category.'/let');
                $db = $letModel->create($data);
                $row = $db->getData();

                $logModel = model('model/dts/approve/' . $category.'/log');

                if(in_array($category, $this->materialArr)) {
                    foreach($params as $item) {
                        $material = Db::name('dts_material_'.$category)->where(['id' => $item['materialId']])->find();
                        if(!$material) {
                            ajaxerror("未查询到物资");
                        }
                        $surplus = bcsub($material['quantity'], $material['consume']);
                        $surplus = bcsub($surplus, $item['quantity']);
                        if($surplus < 0) {
                            ajaxerror("物资数量不足");
                        }
                        //创建记录
                        $logModel->create([$category.'_let_id' => $row['id'], 'material_'.$category.'_id' => $item['materialId'], 'quantity' => $item['quantity']]);
                        //扣除库存
                        Db::name('dts_material_'.$category)->where('id', $material['id'])->update(['consume' => $material['consume'] + $item['quantity']]);
                    }
                }else {
                    foreach($params as $item) {
                        $item[$category.'_let_id'] = $row['id'];
                        $logModel->create($item);
                    }
                }
            }else {
                $model = model('model/dts/approve/' . $category);
                $db = $model->create($data);
                $row = $db->getData();
            }

            return $row;
        });

        try {
            $title = __('Approve ' . $category) . '申请';
            $thing12 = isset($data['forcause']) ? mb_substr($data['forcause'], 0, 20, 'utf-8') : '';
            $weChatData = ['phrase4' => __('Approve '.$category), 'thing12' => $thing12 ? $thing12 : $title, 'thing21' => $admin['nickname'], 'time3' => date("Y-m-d H:i:s", time())];
            //推送公众号
            $apiService = new \app\api\controller\Service;
            $apiService->wechatmessage($data['examine_dept_id'], $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$row['id'], $weChatData);
        }catch(Exception $e) {
            Log::write($e->getMessage());
        }

        $this->success('success');
    }

    //行政审批
    public function approveExamine()
    {

        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        $status = $this->request->post('status');
        $examine_result = $this->request->post('result');
        $refuse = $this->request->post('refuse', '');
        $files = $this->request->post('files');

        if (!$category || !$approveId || !$status) {
            $this->error('请提交拒绝理由');
        }
        if (!in_array($category, $this->categoryArr)) {
            $this->error('行政类型错误');
        }

        //路径在app/common/model
        if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
            $model = model('model/dts/approve/' . $category . '/let');
        }else {
            $model = model('model/dts/approve/' . $category);
        }
        $result = $model->where('id', $approveId)->find();
        if (!$result) {
            $this->error("未找到审批数据");
        }

        $examineId = 0;
        $admin = $this->auth->getAdmininfo();
       
        switch ($category) {
            case 'contract':
            case 'travel':    
                if (!in_array($result['status'], [$this->status_0, $this->status_1, $this->status_2, $this->status_3, $this->status_4])) {
                    $this->error('当前状态不能审批');
                }
                if ($result['status'] == $this->status_0) {
                    $examineId = $result['examine_dept_id'];
                }
                if ($result['status'] == $this->status_1) {
                    $examineId = $result['examine_leader_id'];
                }
                if ($result['status'] == $this->status_2) {
                    $examineId = $result['examine_finance_id'];
                }
                if ($result['status'] == $this->status_3) {
                    $examineId = $result['examine_advisor_id'];
                }
                if ($result['status'] == $this->status_4) {
                    $examineId = $result['examine_legal_id'];
                }
                break;
            case 'carep':
            case 'issues':
            case 'official':
            case 'procure':    
                if (!in_array($result['status'], [$this->status_0, $this->status_1, $this->status_2, $this->status_3])) {
                    $this->error('当前状态不能审批');
                }
                if ($result['status'] == $this->status_0) {
                    $examineId = $result['examine_dept_id'];
                }
                if ($result['status'] == $this->status_1) {
                    $examineId = $result['examine_leader_id'];
                }
                if ($result['status'] == $this->status_2) {
                    $examineId = $result['examine_fenguan_id'];
                }
                if ($result['status'] == $this->status_3) {
                    $examineId = $result['examine_yuanchang_id'];
                }
                break; 
            case 'seal':              
            case 'askfor':
            case 'refuel':
            case 'functional':
            case 'patrol':
            case 'classify':  
            case 'daily':
            case 'expen':  
            case 'food':    
                if ($result['status'] != $this->status_0) {
                    $this->error('当前状态不能审批');
                }
                $examineId = $result['examine_dept_id'];
                break;     
            case 'usecar':
                if (!in_array($result['status'], [$this->status_0])) {
                    $this->error('当前状态不能审批');
                }
                $examineId = $result['examine_vehicle_id'];
                break;
        }

        if ($examineId != $admin['id']) {
            $this->error('审批人不一致');
        }

        $data = ['status' => $status, 'refuse' => $refuse];
        if($category == 'patrol') {
            $data['files'] = $files;
        }

        __db(function () use ($category, $model, $result, $admin, $data, $examine_result, $refuse) {
            //物资拒绝返回库存
            if(in_array($category, $this->materialArr) && $data['status'] == $this->status_2) {
                $list = Db::name('dts_approve_'. $category .'_log')->where($category.'_let_id', $result['id'])->select();
                foreach($list as $item) {
                    $material = Db::name('dts_material_'.$category)->where('id', $item['material_'. $category .'_id'])->find();
                    $consume = bcsub($material['consume'], $item['quantity']);
                    Db::name('dts_material_'.$category)->where('id', $material['id'])->update(['consume' => $consume]);
                }
            }
            //文件归档成功时，把资源库类型更新到附件
            if($category == 'classify' && $data['status'] == $this->status_1) {
                $list = Db::name('dts_approve_'. $category .'_log')->where($category.'_let_id', $result['id'])->select();
                foreach($list as $item) {
                    $urlArr = explode(',', $item['fileurl']);
                    if($urlArr && ($result['config_classify_type_id'] || $result['config_classify_label_id'])) {
                        Db::name('attachment')->where('url', 'in', $urlArr)->update(['category' => $result['config_classify_type_id'], 'subclass' => $result['config_classify_label_id']]);
                    }
                }
            }
            //公车维修审核通过，更新到维修表中
            if($category == 'carep' && $data['status'] == $this->status_2) {
                $configBus = Db::name('dts_config_bus')->where('id', $result['config_bus_id'])->find();
                $faultArr = [
                    'todo_ids' => 0, 'admin_id' => $result['admin_id'], 'deptname' => $result['deptname'], 'category' => 'bus', 'related_id' => $result['id'],
                    'name' => $configBus['name'], 'describes' => $result['forcause'], 'files' => $result['files']
                ];
                model('model/dts/fault/repair')->create($faultArr);
            }
            //更新审批数据
            $model::where('id', $result['id'])->update($data);
            \app\admin\model\dts\approve\examine\Log::create(['category' => $category, 'approve_id' => $result['id'], 'examine_id' => $admin['id'], 'examine_result' => $examine_result, 'examine_refuse' => $refuse]);
        });

        try {
            $apply = \app\admin\model\Admin::where('id', $result['admin_id'])->find();
            $dept = $this->auth->getDeptInfo($apply['dept_id']);  

            $apiService = new \app\api\controller\Service;

            //代办事项
            $title = __('Approve ' . $category) . '审批';

            //发送公众号消息
            $thing12 = isset($result['forcause']) ? mb_substr($result['forcause'], 0, 20, 'utf-8') : '';
            $weChatData1 = ['phrase4' => __('Approve '.$category), 'thing12' => $thing12 ? $thing12 : $title, 'thing21' => $apply['nickname'], 'time3' => date("Y-m-d H:i:s", $result['createtime'])];
            $weChatData2 = ['phrase4' => __('Approve '.$category), 'thing12' => $thing12 ? $thing12 : $title, 'thing16' => $admin['nickname'], 'time15' => date("Y-m-d H:i:s", time())];

            switch($category) {
                case 'contract':
                case 'travel':   
                    if($data['status'] == $this->status_1) {
                        $adminId = $result['examine_leader_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_2) {
                        $adminId = $result['examine_finance_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_3) {
                        $adminId = $result['examine_advisor_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_4) {
                        $adminId = $result['examine_legal_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_5) {//抄送
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                        $copyIds = $result['copy_ids'] ? $result['copy_ids'] : $dept[$category.'_copy_ids'];
                        if($copyIds) {
                            $copyIds = explode(',', $copyIds);
                            foreach ($copyIds as $id) {
                                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                            }
                        }
                    }
                    if(in_array($data['status'], [$this->status_600, $this->status_601, $this->status_602, $this->status_603, $this->status_604])) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break; 
                case 'seal':     
                    if($data['status'] == $this->status_2) {//抄送
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);

                        $copyIds = $result['copy_ids'];
                        if($copyIds) {
                            $copyIds = explode(',', $copyIds);
                            foreach ($copyIds as $id) {
                                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                            }
                        }

                    }
                    if(in_array($data['status'], [$this->status_3])) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;   
                case 'usecar':
                    if($data['status'] == $this->status_2) {
                        $adminId = $result['examine_vehicle_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData1);
                    }
                    if(in_array($data['status'], [$this->status_3])) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;
                case 'carep':
                case 'issues':
                case 'official':
                    if($data['status'] == $this->status_1) {
                        $adminId = $result['examine_leader_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_2) {//抄送
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                        
                        $copyIds = $result['copy_ids'];
                        if($copyIds) {
                            $copyIds = explode(',', $copyIds);
                            foreach ($copyIds as $id) {
                                Log::write('issues--'.$id);
                                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                            }
                        }
                    }
                    if(in_array($data['status'], [$this->status_301, $this->status_302])) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;
                case 'procure':   
                    if($data['status'] == $this->status_1) {
                        $adminId = $result['examine_leader_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_2) {
                        $adminId = $result['examine_fenguan_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_3) {
                        $adminId = $result['examine_yuanchang_id'];
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $adminId);
                        $apiService->wechatmessage($adminId, $apiService->template1, $apiService->jumpUrl($category).'?type=examine&id='.$result['id'], $weChatData1);
                    }
                    if($data['status'] == $this->status_5) {//抄送
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                        
                        $copyIds = $result['copy_ids'];
                        if($copyIds) {
                            $copyIds = explode(',', $copyIds);
                            foreach ($copyIds as $id) {
                                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                            }
                        }
                    }
                    if(in_array($data['status'], [$this->status_300, $this->status_301, $this->status_302, $this->status_303])) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;   
                case 'refuel':
                    if($data['status'] == $this->status_1) {//司机
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $result['enter_driver_id']);
                        $apiService->wechatmessage($result['enter_driver_id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);

                    }
                    if($data['status'] == $this->status_2) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;
                case 'askfor':
                case 'functional':
                case 'patrol':
                case 'classify':  
                    if($data['status'] == $this->status_1) {//抄送
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                        
                        if($category == 'askfor' || $category == 'classify') {
                            $copyIds = $result['copy_ids'];

                            if($copyIds) {
                                $copyIds = explode(',', $copyIds);
                                foreach ($copyIds as $id) {
                                    $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                                }
                            }
                        }
                    }
                    if($data['status'] == $this->status_2) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;
                case 'daily':
                case 'expen':  
                case 'food':
                    if($data['status'] == $this->status_3) {//发送人
                        $weChatData2['phrase5'] = '审批成功';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->savetodoitem($title, $category . '1', $result['giveout_id'], $result['id']);
                        $apiService->wechatmessage($result['giveout_id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);

                        $copyIds = $result['copy_ids'];
                        if($copyIds) {
                            $copyIds = explode(',', $copyIds);
                            foreach ($copyIds as $id) {
                                $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                            }
                        }
                    }
                    if($data['status'] == $this->status_2) {
                        $weChatData2['phrase5'] = '审批驳回';
                        $apiService->edittodoitem($result['todo_id'], $title, $category, $apply['id']);
                        $apiService->wechatmessage($apply['id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                    }
                    break;
            }
        }catch(Exception $e) {
            Log::write($e->getMessage());
        }

        $this->success('success');
    }

    //物资领取
    public function approveClaim()
    {

        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        if (!$category || !$approveId) {
            $this->error('请提交物资信息');
        }
        if (!in_array($category, $this->materialArr)) {
            $this->error('物资类型错误');
        }

        $result = Db::name('dts_approve_' . $category . '_let')->where('id', $approveId)->find();
        if (!$result || $result['status'] != $this->status_4) {
            $this->error('未找到清单或清单状态不匹配');
        }

        __db(function () use ($category, $result) {
            //更新清单
            Db::name('dts_approve_' . $category . '_let')->where('id', $result['id'])->update(['status' => $this->status_5]);
            //发送抄送
            $title = __('Approve ' . $category) . '领取';
            $thing12 = isset($result['forcause']) ? mb_substr($result['forcause'], 0, 20, 'utf-8') : '';
            $thing16 = Db::name('admin')->where('id', $result['examine_dept_id'])->value('nickname');
            $weChatData2 = ['phrase4' => __('Approve '.$category), 'thing12' => $thing12 ? $thing12: $title, 'thing16' => $thing16, 'time15' => date("Y-m-d H:i:s", time())];
            $apiService = new \app\api\controller\Service;
            if(isset($data['copy_ids'])) {
                $copyIds = explode(',', $data['copy_ids']);
                foreach ($copyIds as $id) {
                    $apiService->wechatmessage($id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
                }
            }
        });

        $this->success('success');
    }

    //行政撤回
    public function approveCancel()
    {
        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        if (!$category || !$approveId) {
            $this->error('请选择撤回信息');
        }
        if (!in_array($category, $this->categoryArr)) {
            $this->error('撤回类型错误');
        }

        $dbname = 'dts_approve_' . $category;
        if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
            $dbname = 'dts_approve_' . $category . '_let';
        }
        $result = Db::name($dbname)->where('id', $approveId)->find();
        if (!$result) {
            $this->error('未找到撤回信息');
        }

        $status = 0;

        switch ($category) {
            case 'contract':
            case 'travel':
                $status = $this->status_7;
                break;
            case 'carep':    
            case 'issues':
            case 'official':
            case 'procure':
                $status = $this->status_4;
                break;
            case 'askfor':
            case 'refuel':
            case 'functional':
            case 'patrol':
            case 'classify':     
                $status = $this->status_3;
                break;
            case 'usecar':
            case 'seal':    
            case 'daily':
            case 'expen':  
            case 'food':  
                $status = $this->status_1;
                break;      
        }

        __db(function () use ($category, $status, $result) {
            if (in_array($category, $this->materialArr)) {
                Db::name('dts_approve_' . $category . '_let')->where('id', $result['id'])->update(['status' => $status]);
                $list = Db::name('dts_approve_'. $category .'_log')->where($category.'_let_id', $result['id'])->select();
                foreach($list as $item) {
                    $material = Db::name('dts_material_'.$category)->where('id', $item['material_'. $category .'_id'])->find();
                    $consume = bcsub($material['consume'], $item['quantity']);
                    Db::name('dts_material_'.$category)->where('id', $material['id'])->update(['consume' => $consume]);
                }
            }elseif(in_array($category, $this->letArr)) {
                Db::name('dts_approve_' . $category . '_let')->where('id', $result['id'])->update(['status' => $status]);
            } else {
                Db::name('dts_approve_' . $category)->where('id', $result['id'])->update(['status' => $status]);
            }
            $apiService = new \app\api\controller\Service;
            $apiService->handletodoitem([$result['todo_id']], 0);
        });

        $this->success('success');
    }

    //行政归还
    public function approveReturn()
    {
        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        if (!$category || !$approveId) {
            $this->error('请提交归还信息');
        }
        if (!in_array($category, $this->returnArr)) {
            $this->error('归还类型错误');
        }

        if($category == 'daily') {
            $result = Db::name('dts_approve_'.$category.'_let')->where('id', $approveId)->find();
            if(!$result) {
                $this->error('请选择物资归还');
            }
            //更新清单
            Db::name('dts_approve_' . $category . '_let')->where('id', $approveId)->update(['status' => $this->status_6, 'returntime' => date("Y-m-d H:i:s", time())]);
            $apiService = new \app\api\controller\Service;
            //公众号消息 待办事项
            $title = __('Approve ' . $category) . '归还';
            $thing12 = isset($result['forcause']) ? mb_substr($result['forcause'], 0, 20, 'utf-8') : '';
            $thing16 = Db::name('admin')->where('id', $result['examine_dept_id'])->value('nickname');
            $weChatData2 = ['phrase4' => __('Approve '.$category), 'thing12' => $thing12, 'phrase5' => $title, 'thing16' => $thing16, 'time15' => date("Y-m-d H:i:s", time())];
            $list = $apiService->specialList(624);
            foreach($list as $itme) {
                $apiService->savetodoitem('物资归还', $category . '1', $itme['id'], $approveId);
                if($itme['open_id']) {
                    $apiService->wechatmessagebyopenid($itme['open_id'], $apiService->template2, $apiService->jumpUrl($category), $weChatData2);
                }
            }
        }
        if($category == 'seal') {
            $result = Db::name('dts_approve_'.$category)->where('id', $approveId)->find();
            if(!$result) {
                $this->error('请选择用章归还');
            }
            Db::name('dts_approve_' . $category)->where('id', $approveId)->update(['status' => $this->status_4, 'returntime' => date("Y-m-d H:i:s", time())]);
            $apiService = new \app\api\controller\Service;
            $apiService->edittodoitem($result['todo_id'], '用章归还', $category, $result['examine_dept_id']);
        }

        $this->success('success');
    }

    //行政分配
    public function approveVehicle() {
        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        $config_bus_id = $this->request->post('config_bus_id');
        $enter_driver_id = $this->request->post('enter_driver_id');
        if (!$category || !$approveId || !$config_bus_id || !$enter_driver_id) {
            $this->error('请提交分配信息');
        }
        if ($category != 'usecar') {
            $this->error('分配类型错误');
        }
        $admin = $this->auth->getAdmininfo();
        $item = Db::name('dts_approve_' . $category)->where('id', $approveId)->find();
        if(!$item || $item['examine_vehicle_id'] != $admin['id']) {
            $this->error('分配车管员不一致');
        }
        
        $num = Db::name('dts_approve_' . $category)->where('config_bus_id', $config_bus_id)->whereRaw("fordate >= '".$item['fortime']."'")->count(1);
        if($num) {
            $this->error('车辆使用中，更换车辆');
        }

        $apiService = new \app\api\controller\Service;
        $title = __('Approve '.$category) . '分配';
        __db(function() use($category, $item, $config_bus_id, $enter_driver_id, $apiService, $title) {
            Db::name('dts_approve_' . $category)->where('id', $item['id'])->update(['status' => $this->status_4, 'config_bus_id' => $config_bus_id, 'enter_driver_id' => $enter_driver_id]);
            $apiService->edittodoitem($item['todo_id'], $title, $category, $enter_driver_id);
        });
        //发送公众号
        $thing16 = Db::name('admin')->where('id', $item['examine_vehicle_id'])->value('nickname');
        $weChatData2 = ['phrase4' => __('Approve '.$category), 'thing12' => $title, 'thing16' => $thing16, 'time15' => date("Y-m-d H:i:s", time())];
        $apiService->wechatmessage($enter_driver_id, $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$item['id'], $weChatData2);
        
        $this->success('success');
    }

    //行政登记
    public function approveEnter()
    {
        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        if (!$category || !$approveId) {
            $this->error('请提交登记信息');
        }
        if (!in_array($category, $this->enterArr)) {
            $this->error('登记类型错误');
        }

        $admin = $this->auth->getAdmininfo();
        $item = Db::name('dts_approve_' . $category)->where('id', $approveId)->find();
        if(!$item || $item['enter_driver_id'] != $admin['id']) {
            $this->error('登记司机不一致');
        }

        $data = [];

        if($category == 'usecar') {
            $kilometer = $this->request->post('kilometer');
            $tollfee = $this->request->post('tollfee');
            $parkfee = $this->request->post('parkfee');
            $remark = $this->request->post('remark');
            if(!$kilometer || !$tollfee || !$parkfee) {
                $this->error('请提交登记信息');
            }

            $data = ['status' => $this->status_5, 'kilometer' => $kilometer, 'tollfee' => $tollfee, 'parkfee' => $parkfee, 'remark' => $remark];
        }

        if($category == 'refuel') {
            $specs = $this->request->post('specs');
            $price = $this->request->post('price');
            $volume = $this->request->post('volume');
            $paymoney = $this->request->post('paymoney');
            $files = $this->request->post('files');
            if(!$specs || !$price || !$volume || !$paymoney) {
                $this->error('请提交登记信息');
            }

            $data = ['status' => $this->status_4, 'specs' => $specs, 'price' => $price, 'volume' => $volume, 'paymoney' => $paymoney, 'files' => $files];
        }

        if($data) {
            Db::name('dts_approve_' . $category)->where('id', $approveId)->update($data);
            $apiService = new \app\api\controller\Service;
            $apiService->edittodoitem($item['todo_id'], '信息已登记', $category, $item['admin_id']);
        }
        
        $this->success('success');
    }

    //行政分发
    public function approveDispense()
    {
        $category = $this->request->post('category');
        $approveId = $this->request->post('approveId');
        $dishout_ids = $this->request->post('dishout_ids');
        if (!$category || !$approveId || !$dishout_ids) {
            $this->error('请提交分发信息');
        }
        if ($category != 'official') {
            $this->error('分发类型错误');
        }

        Db::name('dts_approve_' . $category)->where('id', $approveId)->update(['status' => $this->status_5, 'dishout_ids' => $dishout_ids]);

        $this->success('success');
    }

    
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------


    //获取部门审批人
    public function getDeptExamine() {
        
        $category = $this->request->get('category');
        $searchId = $this->request->get('searchId');
        
        $data = [];
        $dept = $this->auth->getDeptInfo();
        if(!$dept) {
            $this->error('未绑定部门信息');
        }

        switch ($category) {
            case 'contract':
            case 'travel':
                $examineArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_dept_ids']))->select();
                $leaderArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_leader_ids']))->select();
                $financeArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_finance_ids']))->select();
                $advisorArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_advisor_ids']))->select();
                $legalArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_legal_ids']))->select();
                $copyArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_copy_ids']))->select();
                $data = ['examineArr' => $examineArr, 'leaderArr' => $leaderArr, 'financeArr' => $financeArr, 'advisorArr' => $advisorArr, 'legalArr' => $legalArr, 'copyArr' => [
                    'copy_ids' => $dept[$category.'_copy_ids'], 
                    'copyavatar' => array_column((array)$copyArr, 'avatar'), 
                    'copyfame' => array_column((array)$copyArr, 'nickname')
                    ]
                ];
                break;
            case 'askfor':
            case 'classify':
                $examineArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_dept_ids']))->select();
                $copyArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_copy_ids']))->select();
                $data = ['examineArr' => $examineArr, 'copyArr' => [
                    'copy_ids' => $dept[$category.'_copy_ids'], 
                    'copyavatar' => array_column((array)$copyArr, 'avatar'), 
                    'copyfame' => array_column((array)$copyArr, 'nickname')
                    ]
                ];
                break;
            case 'usecar':
                $vehicleArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_vehicle_ids']))->select();
                $data = ['vehicleArr' => $vehicleArr];
                break;
            case 'carep':
            case 'official':    
                $examineArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_dept_ids']))->select();
                $leaderArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_leader_ids']))->select();
                $data = ['examineArr' => $examineArr, 'leaderArr' => $leaderArr];
                break;
            case 'issues':
                $examineArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_dept_ids']))->select();
                $leaderArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_leader_ids']))->select();
                $copyArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_copy_ids']))->select();
                $data = ['examineArr' => $examineArr, 'leaderArr' => $leaderArr, 'copyArr' => [
                    'copy_ids' => $dept[$category.'_copy_ids'], 
                    'copyavatar' => array_column((array)$copyArr, 'avatar'), 
                    'copyfame' => array_column((array)$copyArr, 'nickname')
                    ]
                ];
                break;    
            case 'daily':
            case 'expen':
            case 'food':
                $examineArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_examine_ids']))->select();
                $giveoutArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_giveout_ids']))->select();
                $copyArr = Db::name('admin')->field('id,avatar,nickname')->where('id', 'in', explode(',', $dept[$category.'_copy_ids']))->select();
                $data = ['examineArr' => $examineArr, 'giveoutArr' => $giveoutArr, 
                    'copyArr' => ['copy_ids' => $dept[$category.'_copy_ids'], 'copyavatar' => array_column((array)$copyArr, 'avatar'), 'copyfame' => array_column((array)$copyArr, 'nickname')]
                ];
                break; 
            case 'seal':
                $data = Db::name('dts_config_seal')->alias('seal')
                ->field('examine.id,examine.avatar,examine.nickname,seal.copy_ids,GROUP_CONCAT(DISTINCT copy.nickname) as copyfame')
                ->join([
                    ['admin examine', 'examine.id = seal.examine_id', 'left'],
                    ['admin copy', 'FIND_IN_SET(copy.id, seal.copy_ids)', 'left']
                ])
                ->where('seal.id', $searchId)
                ->group('seal.id')
                ->find();
                break;
            case 'refuel':
                $data = Db::name('dts_config_bus')->alias('bus')
                ->field('examine.id,examine.avatar,examine.nickname')
                ->join([
                    ['admin examine', 'examine.id = bus.examine_id', 'left']
                ])
                ->where('bus.id', $searchId)
                ->find();
                break;
            case 'functional':
                $data = Db::name('dts_config_functional')->alias('functional')
                ->field('examine.id,examine.avatar,examine.nickname')
                ->join([
                    ['admin examine', 'examine.id = functional.examine_id', 'left'],
                ])
                ->where('functional.id', $searchId)
                ->find();
                break;
        }

        $this->success('success', $data);
    }

    //行政状态
    public function statusList() {

        $list = Db::name('dts_status')->select();

        $map = new Collection;

        foreach($list as $item) {
            $key = $item['dict_type'];
            if ($map->offsetExists($key)) {
                $obj = $map->offsetGet($key);
                $obj['children'][] = ['status_label' => $item['status_label'], 'status_value' => $item['status_value']];
                $map[$key] = $obj;
            }else {
                $data = ['dict_type' => $item['dict_type'], 'dict_name' => $item['dict_name'], 'children' => []];
                $data['children'][] = ['status_label' => $item['status_label'], 'status_value' => $item['status_value']];

                $map[$key] = $data;
            }
        }

        $this->success('success', array_values($map->toArray()));
    }

    //故障列表
    public function faultList() {

        $category = $this->request->get('category');
        if(!in_array($category, ['fault', 'material'])) {
            $this->error('故障类型有误');
        }
        $search = $this->request->get('search');

        $url = 'api/admin/approve/fault';
        $authority = new \app\api\controller\admin\Authority;
        $falg = $authority->isAuth($url);
        if(!$falg) {
            $this->error('无权限，请联系管理员');
        }
        
        $query0 = [];
        if(in_array($category, ['fault'])) {
            $query0 = $search ? ['log.location' => ['LIKE', '%'.$search.'%']] : [];
        }
        if(in_array($category, ['material'])) {
            $query0 = $search ? ['log.name' => ['LIKE', '%'.$search.'%']] : [];
        }

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $admin = $this->auth->getAdmininfo();

        $query1 = ['log.category' => $category];
        $query2 = ['log.admin_id' => $admin['id']];

        $list = Db::name('dts_fault_repair')->alias('log')
        ->field('log.*,FROM_UNIXTIME(log.createtime,"%Y-%m-%d %H:%i") as createtime,admin.nickname as adminfame,repair.nickname as repairfame')
        ->join([
            ['admin admin', 'admin.id = log.admin_id', 'left'],
            ['admin repair', 'repair.id = log.repair_id', 'left']
        ])
        ->where(array_merge($query0, $query1, $query2))
        ->order('log.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //故障发起
    public function faultApply() {
        $category = $this->request->post('category');
        if(!in_array($category, ['fault', 'material'])) {
            $this->error('故障类型有误');
        }
        $name = $this->request->post('name');
        $location = $this->request->post('location');
        $severity = $this->request->post('severity');
        $describes = $this->request->post('describes');
        $files = $this->request->post('files');

        if(!$describes || !$files) {
            $this->error('请提交故障信息');
        }

        $admin = $this->auth->getAdmininfo();
        $dept = $this->auth->getDeptInfo();
        if(!$dept) {
            $this->error('未绑定部门信息');
        }

        $data = [
            'todo_ids' => 0, 'admin_id' => $admin['id'], 'deptname' => $dept['name'], 'category' => $category, 'name' => $name, 
            'location' => $location, 'describes' => $describes, 'files' => $files
        ];
        if($severity) {
            $data['severity'] = $severity;
        }
        $db = \app\common\model\dts\fault\Repair::create($data);
        $row = $db->getData();
        
        //查询是分配主任的人员
        $todoIdArr = [];
        $apiService = new \app\api\controller\Service;
        $list = $apiService->specialList(628);
        if($list) {
            //待办事项
            foreach($list as $item) {
                $todo = $apiService->savetodoitem($name, 'repair', $item['id'], $row['id']);
                $todoIdArr[] = $todo['id'];
            }
        }
        if($todoIdArr) {
            \app\common\model\dts\fault\Repair::where('id', $row['id'])->update(['todo_ids' => join(',', $todoIdArr)]);
        }

        $this->success('success');
    }

    //故障详情
    public function faultInfo() {
    
        $logId = $this->request->get('logId', 0);
        
        $info = Db::name('dts_fault_repair')->alias('log')
        ->field('log.*,FROM_UNIXTIME(log.createtime,"%Y-%m-%d %H:%i") as createtime,admin.nickname as adminfame,repair.nickname as repairfame')
        ->join([
            ['admin admin', 'admin.id = log.admin_id', 'left'],
            ['admin repair', 'repair.id = log.repair_id', 'left']
        ])
        ->where('log.id', $logId)
        ->find();

        $this->success('success', $info);
    }

    //工资分类列表
    public function wagesCategoryList() {

        $title = $this->request->get('title');
        $query = $title ? ['dw.title' => ['LIKE', '%'.$title.'%']] : [];

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = Db::name('dts_wages')->alias('dw')->field('dw.*,FROM_UNIXTIME(dw.createtime,"%Y-%m-%d %H:%i:%s") as createtime')->where($query)->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //工资、绩效列表
    public function wagesList() {

        $category = $this->request->get('category');
        if(!in_array($category, ['bar', 'merits'])) {
            $this->error('请选择查询数据');
        }
        
        $url = 'api/admin/approve/wages';
        $authority = new \app\api\controller\admin\Authority;
        $falg = $authority->isAuth($url);
        if(!$falg) {
            $this->error('无权限，请联系管理员');
        }

        $admin = $this->auth->getAdmininfo();
        $query = ['wages.username' => $admin['nickname']];
  
        $list = Db::name('dts_wages_'.$category)->alias('wages')
        ->join('dts_wages dw', 'dw.id=wages.dts_wages_id', 'left')
        ->field('wages.id,wages.username,wages.payable_total,wages.actual_total,dw.title,dw.createby,FROM_UNIXTIME(dw.createtime,"%Y-%m-%d %H:%i:%s") as createtime')
        ->where($query)
        ->select();

        $this->success('success', $list);
    }

    //工资、绩效详情
    public function wagesInfo() {

        $wagesId = $this->request->get('wagesId');
        $type = $this->request->get('type'); // 0=行政, 1=通知
        $category = $this->request->get('category');
        if(!$wagesId || !in_array($category, ['bar', 'merits'])) {
            $this->error('请选择查询信息');
        }

        $query = ['category.id' => $wagesId];
        if($type) {
            $query = ['category.dts_wages_id' => $wagesId, 'username' => $this->auth->nickname];
        }

        $info = Db::name('dts_wages_'.$category)->alias('category')
        ->field('category.*,FROM_UNIXTIME(wages.createtime,"%Y-%m-%d %H:%i:%s") as createtime')
        ->join('dts_wages wages', 'wages.id = category.dts_wages_id', 'left')
        ->where($query)
        ->find();

        $this->success('success', $info);
    }


    //查询撤销信息
    public function getRevokeInfo() {

        $status = 0;
        $category = $this->request->get('category');
        switch ($category) {
            case 'contract':
            case 'travel':
                $status = $this->status_7;
                break;
            case 'carep':    
            case 'issues':
            case 'official':
            case 'procure':
                $status = $this->status_4;
                break;
            case 'askfor':
            case 'refuel':
            case 'functional':
            case 'patrol':
            case 'classify':     
                $status = $this->status_3;
                break;
            case 'usecar':
            case 'seal':    
            case 'daily':
            case 'expen':  
            case 'food':  
                $status = $this->status_1;
                break;      
        }

        $admin = $this->auth->getAdmininfo();
        if($status == 0) {
            $this->success('success', ['category' => $category, 'admin_id' => $admin['id'], 'status' => $status, 'approve_id' => 0]);
        }

        $dbname = 'dts_approve_' . $category;
        if(in_array($category, $this->materialArr) || in_array($category, $this->letArr)) {
            $dbname = 'dts_approve_' . $category . '_let';
        }

        $info = Db::name($dbname)->where(['admin_id' => $admin['id'], 'status' => $status])->order('id', 'desc')->limit(1)->find();
        if($info) {
            $this->success('success', ['category' => $category, 'admin_id' => $admin['id'], 'status' => $status, 'approve_id' => $info['id']]);
        }

        $this->success('success', ['category' => $category, 'admin_id' => $admin['id'], 'status' => $status, 'approve_id' => 0]);
    }
}
